package demo.main;

import static net.sf.dynamicreports.report.builder.DynamicReports.col;
import static net.sf.dynamicreports.report.builder.DynamicReports.report;
import static net.sf.dynamicreports.report.builder.DynamicReports.type;

import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;

import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

public class IReportTemplate extends MutiReport {
	@At("/getIReportTemplate")
	@Ok("json")
	public String getIReportTemplate(HttpServletRequest request,
			HttpServletResponse response) {
		System.out.println("getIReportTemplate");
		build(request, response);
		return resultResult;
	}

	protected void build(HttpServletRequest request,
			HttpServletResponse response) {
		InputStream is = request.getSession().getServletContext()
				.getResourceAsStream("jrxml/ireport-1.jrxml");
		System.out.println("is is null : " + (is == null));
		try {
			reportBuilder = report()
					//.setTemplate(Templates.reportTemplate)
					.setTemplateDesign(is)
					/*.columns(
							col.column("产品", "item", type.stringType()),
							col.column("数量", "quantity",
									type.integerType()),
							col.column("单价", "unitprice",
									type.integerType()))*/
					//.title(Templates.createTitleComponent(""))
					.setDataSource(createDataSource());
			setResult(reportBuilder.toJasperPrint(), request, response);
		} catch (DRException e) {
			e.printStackTrace();
		}
	}

	private JRDataSource createDataSource() {
		DataSource dataSource = new DataSource("item", "quantity", "unitprice");
		for (int i = 0; i < 10; i++) {
			dataSource.add("图书", (int)((Math.random() * 10) + 1),
					(int) (Math.random() * 100) + 1);
		}
		return dataSource;
	}
}
